package com.raycloud.erp.omll.provider.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.omall.open.sdk.domain.OrderListInfo;
import com.omall.open.sdk.domain.RefundInfo;
import com.raycloud.erp.omll.data.entity.Order;
import com.raycloud.erp.omll.data.entity.Trade;
import com.raycloud.erp.omll.provider.constant.OmallRefundStatus;
import com.raycloud.erp.omll.provider.constant.OmallTradeStatus;
import com.raycloud.erp.omll.provider.model.bo.TbTradeBO;
import com.raycloud.erp.omll.provider.model.vo.OrderCopierVo;
import com.raycloud.erp.omll.provider.model.vo.TradeCopierVo;
import com.raycloud.erp.omll.provider.utils.PlatformStringUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author 枫伦
 * @description: 洋葱交易单拷贝助手
 * @date 2020/10/23 9:57 上午
 */
@Component
@Slf4j
public class OmallTradeCopier {

    @Autowired
    OmallOrderCopier orderCopier;

    public TbTradeBO copy(TradeCopierVo tradeCopierVo, Trade trade) {
        //填充基本的信息
        fillBaseInfo(tradeCopierVo, trade);
        //填充弄收货信息
        fillAddressInfo(tradeCopierVo, trade);
        //卖家备注,只有卖家才能查看该字段
        trade.setSellerMemo(removeEmojis(tradeCopierVo.getSplitOrderMsg()));
        //订单相关的价格信息
        fillPayInfo(tradeCopierVo, trade);
        //对优惠信息进行处理
        handlePromotion(tradeCopierVo, trade);
        // 添加订单详情 为交易trade逐个添加订单Order(添加子订单)
        List<Order> orderList = productOrderList(tradeCopierVo, trade);
        //处理trade的状态
        handleTradeStatus(tradeCopierVo, orderList, trade);
        //处理order的状态
        handleOrderStatus(trade, orderList);

        // 自动修正金额数据 原来的金额字段是String类型的.用新协议写的时候这边已经是以分为单位了
//        PaymentUtils.checkTrade(trade);
        return new TbTradeBO(trade, orderList);
    }

    private void fillBaseInfo(TradeCopierVo orderInfo, Trade trade) {
        trade.setSource(orderInfo.getPlatformName());
        //平台订单号
        trade.setTid(orderInfo.getPlatformCode());
        //下单时间
        trade.setCreated(orderInfo.getPlatformCreate());
        //付款时间
        trade.setPayTime(orderInfo.getPaidTime());
        //订单在平台上的修改时间
        trade.setModified(orderInfo.getUpdateTime());
    }

    private void fillPayInfo(TradeCopierVo orderInfo, Trade target) {
        //通过订单的详细信息设置订单对应相关的字段信息的值
        int payment = 0;
        if (orderInfo.getOrderDetails() != null) {
            for (OrderCopierVo orderDetail : orderInfo.getOrderDetails()) {
                payment += orderDetail.getPrice() == null ? 0 : orderDetail.getPrice();
            }
        }
        payment += orderInfo.getFreight();
        //总优惠金额 = 抵扣金额(分) + 满减金额(分) + 使用积分金额(分)
        int totalDiscountFee = orderInfo.getDiscountPrice() + orderInfo.getFullDecrPrice() + orderInfo.getIntegPrice();
        // 公式 payment = totalFee + postFee - totalDiscountFee
        int totalFee = payment + totalDiscountFee - orderInfo.getFreight();
        //实付金额
        target.setPayment(Long.valueOf(payment));
        //商品金额
        target.setTotalFee(Long.valueOf(totalFee));
        //运费
        target.setPostFee(Long.valueOf(orderInfo.getFreight()));

    }

    private void fillAddressInfo(OrderListInfo orderInfo, Trade trade) {
        //省市区Json(发往国外的订单的省市区均为海外)
        if (StringUtils.isNotEmpty(orderInfo.getLogisticsAddressJson())) {
            JSONObject address = JSON.parseObject(orderInfo.getLogisticsAddressJson());
            trade.setReceiverState(address.getString("province"));
            trade.setReceiverCity(address.getString("city"));
            trade.setReceiverDistrict(address.getString("country"));
        }
        //平台订单上的买家昵称
        trade.setBuyerNick(orderInfo.getLogisticsConsignee());
        //收货地址
        String address = orderInfo.getLogisticsAddress();
        //收货人的省份
        if (trade.getReceiverState() != null) {
            address = address.replaceFirst(trade.getReceiverState(), "");
        }
        //收货人所在的城市
        if (trade.getReceiverCity() != null) {
            address = address.replaceFirst(trade.getReceiverCity(), "");
        }
        //收货人所在的区
        if (trade.getReceiverDistrict() != null) {
            address = address.replaceFirst(trade.getReceiverDistrict(), "");
        }
        //收货人的详细地址
        trade.setReceiverAddress(address);
        //收货人的姓名
        trade.setReceiverName(PlatformStringUtils.replaceUtf8mb4(orderInfo.getLogisticsConsignee()));
        //收货人的移动
        trade.setReceiverMobile(orderInfo.getLogisticsPhone());
        //洋葱平台没有返回邮编信息
//        trade.setReceiverZip(orderInfo.getDeliveryPostalCode());

    }

    /**
     * 移除特殊字符
     */
    protected static String removeEmojis(String str) {
        if (StringUtils.isEmpty(str)) {
            return str;
        }
        try {
            str = PlatformStringUtils.replaceUtf8mb4(str);
        } catch (Exception e) {
            log.error("removeEmojis failed, str:" + str, e);
        }
        return str;
    }

    /**
     * 处理优惠信息
     *
     * @param orderInfo
     * @param target
     */
    private void handlePromotion(OrderListInfo orderInfo, Trade target) {
        //卖家手调整的金额
        if (target.getAdjustFee() == null) {
            target.setAdjustFee(0L);
        }
        //查询系统优惠金额
        if (target.getDiscountFee() == null) {
            target.setDiscountFee(Long.valueOf(orderInfo.getDiscountPrice() + orderInfo.getFullDecrPrice() + orderInfo.getIntegPrice()));
        }
    }

    /**
     * 产生orderList
     *
     * @return
     */
    private List<Order> productOrderList(TradeCopierVo tradeCopierVo, Trade trade) {
        List<Order> orderList = new ArrayList<>();
        //如果订单详细信息接口有返回数据,那就证明订单是存在子订单信息或者是商品信息的.
        if (tradeCopierVo.getOrderDetails() != null) {
            for (OrderCopierVo orderCopierVo : tradeCopierVo.getOrderDetails()) {
                // 得到订单详情
                Order order = orderCopier.copy(orderCopierVo, new Order());
                order.setTid(trade.getTid());
                order.setPayTime(trade.getPayTime());
                order.setModified(trade.getModified());
                order.setConsignTime(trade.getConsignTime());
                order.setEndTime(trade.getEndTime());
                order.setCreated(trade.getCreated());
                //卖家昵称
                order.setSellerNick(trade.getSellerNick());
                List<RefundInfo> refundInfos = tradeCopierVo.getRefundInfoListMap().get(orderCopierVo.getSupplySkuCode());
                if (CollectionUtils.isNotEmpty(refundInfos)) {
                    String orderRefundStatus = getOrderRefundStatus(refundInfos);
                    order.setRefundStatus(OmallRefundStatus.getRefundStatus(orderRefundStatus));
                }

                orderList.add(order);
            }
        }
        return orderList;
    }

    /**
     * 1. 只要包含待审核的 -> 退款审核中
     * 2.包含审核通过，但是不包含待审核的 -> 已退款
     * 3.只包含审核不通过 -> 拒绝退款
     *
     * @param refundInfos
     * @return
     */
    private String getOrderRefundStatus(List<RefundInfo> refundInfos) {
        List<RefundInfo> waitList = refundInfos.stream().filter(refundInfo -> OmallRefundStatus.REFUND_STATUS_WAIT.equals(refundInfo.getReturnStatus())).collect(Collectors.toList());
        if (CollectionUtils.isNotEmpty(waitList)) {
            return OmallRefundStatus.REFUND_STATUS_WAIT;
        }
        List<RefundInfo> passedList = refundInfos.stream().filter(refundInfo -> OmallRefundStatus.REFUND_STATUS_PASSED.equals(refundInfo.getReturnStatus())).collect(Collectors.toList());
        if (CollectionUtils.isNotEmpty(passedList)) {
            return OmallRefundStatus.REFUND_STATUS_PASSED;
        }
        List<RefundInfo> notPassedList = refundInfos.stream().filter(refundInfo ->
                OmallRefundStatus.REFUND_STATUS_NOT_PASSED.equals(refundInfo.getReturnStatus())
                        || OmallRefundStatus.REFUND_STATUS_REJECT.equals(refundInfo.getReturnStatus())
                        || OmallRefundStatus.REFUND_STATUS_SREJECT.equals(refundInfo.getReturnStatus())
        ).collect(Collectors.toList());
        if (CollectionUtils.isNotEmpty(notPassedList)) {
            return OmallRefundStatus.REFUND_STATUS_NOT_PASSED;
        }
        return "";
    }


    /**
     * 处理trade的状态
     *
     * @param tradeCopierVo
     * @param orderList
     * @param trade
     */
    private void handleTradeStatus(TradeCopierVo tradeCopierVo, List<Order> orderList, Trade trade) {
        if (CollectionUtil.isEmpty(orderList)) {
            return;
        }
        List<Order> refundWaitOrders = orderList.stream().filter(
                tbOrder -> OmallRefundStatus.getRefundStatus(OmallRefundStatus.REFUND_STATUS_WAIT).equals(tbOrder.getRefundStatus())).collect(Collectors.toList());
        if (CollectionUtils.isNotEmpty(refundWaitOrders)) {
            trade.setStatus(OmallTradeStatus.getTradeStatusMapKey(tradeCopierVo.getLogisticsStatus(), tradeCopierVo.getReturnStatus(), OmallRefundStatus.REFUND_STATUS_WAIT));
            return;
        }
        List<Order> refundPassedOrders = orderList.stream().filter(
                tbOrder -> OmallRefundStatus.getRefundStatus(OmallRefundStatus.REFUND_STATUS_PASSED).equals(tbOrder.getRefundStatus())
        ).collect(Collectors.toList());
        if (CollectionUtils.isNotEmpty(refundPassedOrders)) {
            trade.setStatus(OmallTradeStatus.getTradeStatusMapKey(tradeCopierVo.getLogisticsStatus(), tradeCopierVo.getReturnStatus(), OmallRefundStatus.REFUND_STATUS_PASSED));
            return;
        }
        List<Order> refundNotPassedOrders = orderList.stream().filter(
                tbOrder -> OmallRefundStatus.getRefundStatus(OmallRefundStatus.REFUND_STATUS_NOT_PASSED).equals(tbOrder.getRefundStatus())
        ).collect(Collectors.toList());
        if (CollectionUtils.isNotEmpty(refundNotPassedOrders)) {
            trade.setStatus(OmallTradeStatus.getTradeStatusMapKey(tradeCopierVo.getLogisticsStatus(), tradeCopierVo.getReturnStatus(), OmallRefundStatus.REFUND_STATUS_NOT_PASSED));
            return;
        }
        trade.setStatus(OmallTradeStatus.getTradeStatusMapKey(tradeCopierVo.getLogisticsStatus(), tradeCopierVo.getReturnStatus(), null));
    }

    /***
     * @DESCRIPTION: 处理子订单或者商品的装潢题啊
     * @author 枫伦
     * @params: [trade, orderList]
     * @return: void
     * @Date: 2021/1/11 11:34 上午 
     * @Modified By:  
     */
    private void handleOrderStatus(Trade trade, List<Order> orderList) {
        for (Order order : orderList) {
            order.setStatus(trade.getStatus());
        }
    }

}
